"""
数据生成工具类 - 集成create_data_template.py中的数据生成方法
"""
import sys
import os
import random
from typing import Dict, Any, List
from faker import Faker

# 添加scripts目录到路径
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "scripts"))

# 导入数据模板中的生成方法
from create_data_template import (
    generate_phone, generate_decimal, generate_number,
    generate_datetime, generate_date, generate_text,
    generate_email, generate_option, generate_multilingual,
    generate_rich_text, generate_bigint
)

# 导入无效数据生成方法 - 使用importlib处理带空格的模块名
import importlib.util
spec = importlib.util.spec_from_file_location(
    "create_data_template_copy", 
    os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "scripts", "create_data_template.py")
)
create_data_template_copy = importlib.util.module_from_spec(spec)
spec.loader.exec_module(create_data_template_copy)

# 从copy模块导入无效数据生成函数
generate_phone_invalid = create_data_template_copy.generate_phone_invalid
generate_decimal_invalid = create_data_template_copy.generate_decimal_invalid
generate_number_invalid = create_data_template_copy.generate_number_invalid
generate_datetime_invalid = create_data_template_copy.generate_datetime_invalid
generate_date_invalid = create_data_template_copy.generate_date_invalid
generate_text_invalid = create_data_template_copy.generate_text_invalid
generate_email_invalid = create_data_template_copy.generate_email_invalid
generate_option_invalid = create_data_template_copy.generate_option_invalid
generate_multilingual_invalid = create_data_template_copy.generate_multilingual_invalid
generate_rich_text_invalid = create_data_template_copy.generate_rich_text_invalid
generate_bigint_invalid = create_data_template_copy.generate_bigint_invalid
generate_boolean_invalid = create_data_template_copy.generate_boolean_invalid

# 初始化Faker
fake_zh = Faker("zh_CN")
fake_en = Faker("en_US")
Faker.seed(42)

class DataGenerator:
    """数据生成工具类"""
    
    def __init__(self):
        # 字段类型映射：字段类型 -> 生成方法
        self.type_generators = {
            # 正常数据生成器
            "mobileNumber": generate_phone,
            "decimal": generate_decimal,
            "number": generate_number,
            "datetime": generate_datetime,
            "richText": generate_rich_text,
            "multilingual": generate_multilingual,
            "date": generate_date,
            "option": generate_option,
            "text": generate_text,
            "bigint": generate_bigint,
            "boolean": lambda: random.choice([True, False]),
            "email": generate_email,
    
            
            # 异常数据生成器
            "mobileNumber_invalid": generate_phone_invalid,
            "decimal_invalid": generate_decimal_invalid,
            "number_invalid": generate_number_invalid,
            "datetime_invalid": generate_datetime_invalid,
            "richText_invalid": generate_rich_text_invalid,
            "multilingual_invalid": generate_multilingual_invalid,
            "date_invalid": generate_date_invalid,
            "option_invalid": generate_option_invalid,
            "text_invalid": generate_text_invalid,
            "bigint_invalid": generate_bigint_invalid,
            "boolean_invalid": generate_boolean_invalid,
            "email_invalid": generate_email_invalid
        
        }
    
    def generate_field_data(self, field_name: str, field_type: str, is_valid: bool = True) -> Any:
        """
        为指定字段生成数据
        
        Args:
            field_name: 字段名称
            field_type: 字段类型
            is_valid: 是否生成有效数据
            
        Returns:
            生成的数据
        """
        # 构建生成器键名
        generator_key = f"{field_type}_invalid" if not is_valid else field_type
        
        # 获取生成器方法
        generator = self.type_generators.get(generator_key)
        
        if generator:
            try:
                # 对于text字段，需要传入max_len参数
                if field_type == "text" and is_valid:
                    return generator(100)  # 传入默认长度100
                else:
                    return generator()
            except Exception as e:
                print(f"生成字段 {field_name} ({field_type}) 数据时出错: {str(e)}")
                return None
        else:
            print(f"未找到字段类型 {field_type} 的生成器")
            return None
    
    def generate_test_data(self, fields: List[Dict[str, Any]], is_valid: bool = True) -> Dict[str, Any]:
        """
        为所有字段生成测试数据
        
        Args:
            fields: 字段信息列表
            is_valid: 是否生成有效数据
            
        Returns:
            包含所有字段数据的字典
        """
        test_data = {}
        
        for field in fields:
            field_name = field.get('field_api_name')
            field_type = field.get('field_type', 'text')
            
            if field_name:
                data = self.generate_field_data(field_name, field_type, is_valid)
                if data is not None:
                    test_data[field_name] = data
        
        return test_data
    
    def generate_complete_record(self, is_valid: bool = True) -> Dict[str, Any]:
        """
        生成完整的记录数据
        
        Args:
            is_valid: 是否生成有效数据
            
        Returns:
            完整的记录数据
        """
        # 定义所有支持的字段
        all_fields = [
            {"field_api_name": "phone_73c280f2783", "field_type": "mobileNumber"},
            {"field_api_name": "decimal_a446e77c109", "field_type": "decimal"},
            {"field_api_name": "number_a33398bfae5", "field_type": "number"},
            {"field_api_name": "datetime_bfae52d8694", "field_type": "datetime"},
            {"field_api_name": "richText_76d22d35024", "field_type": "richText"},
            {"field_api_name": "multilingual_24673c280f2", "field_type": "multilingual"},
            {"field_api_name": "date_398bfae52d8", "field_type": "date"},
            {"field_api_name": "option_e52d86948bb", "field_type": "option"},
            {"field_api_name": "text_7ea7d6a3339", "field_type": "text"},
            {"field_api_name": "bigint_7d6a33398bf", "field_type": "bigint"},
            {"field_api_name": "boolean_e206a267520", "field_type": "boolean"},
            {"field_api_name": "email_f2783b49d9a", "field_type": "email"},
        ]
        
        return self.generate_test_data(all_fields, is_valid)

# 全局数据生成器实例
data_generator = DataGenerator() 